import { message } from "@/utils/message";
import {
  getAttachDataList,
  delAttachData,
  getDict
} from "@/api/data";
import { reactive, ref, onMounted, toRaw, h } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { Result } from "@/utils/http/utils";
import { deviceDetection, downloadByData, downloadByOnlineUrl, downloadByUrl } from "@pureadmin/utils";

export function useRole() {
  const form = reactive({
    page: 1,
    pageSize: 10,
    mimeType: "",
    originame: ""
  });

  const treeData = ref([]);
  const treeLoading = ref(true);
  const dataList = ref([]);
  const loading = ref(true);

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "预览",
      cellRenderer: ({ row }) => {
        const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg'];
        const isImage = imageExtensions.some(ext => row.url.toLowerCase().endsWith(ext));
        if (isImage) {
          return (
            <el-image
              preview-teleported={true}
              src={row.fullUrl + row.url}
              preview-src-list={Array.of(row.fullUrl + row.url)}
              class="w-[24px] h-[24px] rounded-full align-middle"
            />
          );
        } else {
          const fileExtension = row.url.split('.').pop();
          return <span style={{
            display: 'inline-block',
            padding: '4px 8px',
            color: '#409EFF',
            fontSize: '16px',
            textAlign: 'center',
          }}>{fileExtension}</span>;
        }
      },
      minWidth: 60
    },
    {
      label: "储蓄名称",
      prop: "objectName",
      minWidth: 120
    },
    {
      label: "原文件名",
      prop: "originName",
      minWidth: 80
    },
    {
      label: "存储模式",
      prop: "storageMode",
      minWidth: 120
    },
    {
      label: "资源类型",
      prop: "mimeType",
      minWidth: 80
    },
    {
      label: "文件大小",
      prop: "sizeInfo",
      minWidth: 80
    },
    {
      label: "上传时间",
      prop: "created_at",
      minWidth: 120
    },
    {
      label: "操作",
      fixed: "right",
      width: 230,
      slot: "operation"
    }
  ];
  
  function handleUpdate(row) {
    console.log(row);
  }

  function handleDelete(row) {
    delAttachData({ id: row.id })
      .then((result: Result) => {
        if (result && result.code == 200) {
          message("操作成功", { type: "success" });
          onSearch();
        }
      })
      .catch(error => {
        console.error("请求失败:", error);
      });
  }

  function isBlob(obj: any): obj is Blob {
    return obj instanceof Blob;
  }

  function download(row) {
    const fullUrl = row.fullUrl + row.url;
    const fileName = row.originName || row.objectName;
    const imageFormats = ["png", "jpeg", "jpg", "gif", "webp", "bmp", "svg", "tiff"];
    // 判断后执行相应的下载函数
    const isImageFile = imageFormats.includes(row.suffix);
    isImageFile ? downloadByOnlineUrl(fullUrl, fileName) : downloadByUrl(fullUrl, fileName);
  }

  function handleSizeChange(val: number) {
    form.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    form.page = val;
    onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  async function onSearch() {
    loading.value = true;
    const { data } = await getAttachDataList(toRaw(form));
    dataList.value = data.list;
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.currentPage;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function onTreeSelect({ id, selected }) {
    form.mimeType = selected ? id : "";
    onSearch();
  }

  interface TransformedItem {
    id: string;
    name: string;
  }

  onMounted(async () => {
    treeLoading.value = true;
    const { data } = await getDict({ code: "attachment_type" });
    const data2: TransformedItem[] = data.map(item => ({
      id: item.value,
      name: item.label
    }));
    data2.unshift({ id: "", name: "所有" });
    treeData.value = data2;
    treeLoading.value = false;
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    treeData,
    treeLoading,
    onTreeSelect,
    deviceDetection,
    onSearch,
    resetForm,
    handleCurrentChange,
    handleUpdate,
    download,
    handleDelete,
    handleSizeChange,
    handleSelectionChange
  };
}
